<?php

namespace App\Common;


use App\Traits\TraitConnectDB;

class SessionHandlerRedis implements \SessionHandlerInterface
{
    use TraitConnectDB;


    /**
     * 获取redis key
     *
     * @param $session_id
     * @return string
     */
    private function funcGetKeyFix__redis($session_id)
    {
        return "XSESSION:{$session_id}";
    }

    public function close()
    {
        //控制器自动回收

        \h::funcLog(__METHOD__, 'session 回收');
    }

    public function destroy($session_id)
    {
//        var_dump('destroy');
//        $this->redis()->expire($this->funcGetKeyFix__redis($session_id), 1);
        $this->redis()->del($this->funcGetKeyFix__redis($session_id));
    }

    public function gc($maxlifetime)
    {
        //后续实现。
    }

    public function open($save_path, $name)
    {
        return true;
    }

    public function read($session_id)
    {
        $str = $this->redis()->get($this->funcGetKeyFix__redis($session_id));

        return $str;
    }

    public function write($session_id, $session_data)
    {
        if (!empty(unserialize($session_data)))
        {
            $timeout = 1 * 60 * 60;

            $this->redis()->set($this->funcGetKeyFix__redis($session_id), $session_data, $timeout);
        }

        return true;
    }
}